package noema.humanTask;

import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import noema.dataModel.MyTask;
import noema.interceptor.LoggerInterceptor;
import noema.session.SessionFactory;

import org.drools.runtime.StatefulKnowledgeSession;

import flexjson.JSONDeserializer;
import flexjson.JSONException;


@Interceptors({LoggerInterceptor.class})
@Stateless
public class HumanTaskManagerImpl implements HumanTaskManager {
	@PersistenceContext(unitName = "application.data")
	EntityManager em;
	@EJB
	SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<MyTask> retrieveTaskList() {
		return em.createQuery("SELECT t FROM MyTask t").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MyTask> retrieveTaskListByProcessInstance(long id) {
		Query q = em.createQuery("SELECT t FROM MyTask t WHERE t.processInstanceId=:id");
		q.setParameter("id", id);
		return q.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MyTask> retrieveTaskListByName(String name) {
		Query q = em.createQuery("SELECT t FROM MyTask t WHERE t.name=:name");
		q.setParameter("name", name);
		return q.getResultList();
	}

	@Override
	public void completeTask(long id, String performer, String jsonParams) {
		MyTask task = em.find(MyTask.class, id);
		if (task != null) {
			StatefulKnowledgeSession ksession = sessionFactory
					.getSessionByProcessInstanceId(task.getProcessInstanceId());
			JSONDeserializer<Map<String,Object>> deserializer=new JSONDeserializer<Map<String,Object>>();
			try{
				Map<String, Object> resultParams=deserializer.deserialize(jsonParams);
				ksession.getWorkItemManager().completeWorkItem(task.getId(), resultParams);
				em.remove(task);
			}catch(JSONException e){
				throw new IllegalArgumentException("jsonResultData isn't in JSON format");
			}finally{
				ksession.dispose();
			}
		}
	}

	@Override
	public void abortTask(long id) {
		MyTask task = em.find(MyTask.class, id);
		if (task != null) {
			StatefulKnowledgeSession ksession = sessionFactory
					.getSessionByProcessInstanceId(task.getProcessInstanceId());
			ksession.getWorkItemManager().abortWorkItem(task.getId());
			ksession.dispose();
			em.remove(task);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MyTask> retrieveTaskListByPotentialOwner(String owner) {
		Query q=em.createQuery("SELECT t FROM MyTask t WHERE t.potentialOwner = :owner");
		q.setParameter("owner", owner);
		return q.getResultList();
	}

}
